<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">


      <el-date-picker
        v-model="listQuery.startToEnd"
        :picker-options="pickerOptions"
        type="daterange"
        align="right"
        unlink-panels
        range-separator=" 至 "
        start-placeholder="开始日期"
        end-placeholder="结束日期"/>

      <el-select v-model="listQuery.ucstomerName" filterable clearable placeholder="用户名">
        <el-option
          v-for="(value, key) in customerNames"
          :key="key"
          :label="value"
          :value="value"/>
      </el-select>

      <el-select v-model="extraParam.batchNumber" clearable placeholder="请选择产品批号">
        <el-option
          v-for="(value, key) in batchNumbers"
          :key="key"
          :label="value"
          :value="key"/>

      </el-select>


      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <br></br>
          <el-tabs type="border-card">
            <el-tab-pane label="订单上传">

            </el-tab-pane>
            <el-tab-pane label="配置管理">配置管理</el-tab-pane>
            <el-tab-pane label="角色管理">角色管理</el-tab-pane>
            <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane>
          </el-tabs>
      <div class="input-container">
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="handleUpdate2">编辑
      </el-button>

      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getProductInfo">查看分装统计
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getCF">查看合格证</el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="showStocks">查看备货</el-button>
        <el-lable style="width: 80px;">抽样：</el-lable>
        <el-input size="mini" class="filter-item" placeholder="抽样体积" width="80" v-model="samples.drawSample"></el-input>
        <el-lable style="width: 80px;">留样：</el-lable>
      <el-input size="mini" class="filter-item" placeholder="留样体积" width="80" v-model="samples.keepSample"></el-input>
      </div>


      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getTotalInfo">生成总表
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getSplitSheets">生成分装单
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getSplitSheets2">生成分装清单
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getShipAccord">生成发运记录
      </el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-edit" @click="getOAAccord">生成导入OA表
      </el-button>


      <el-upload
        :limit="5"
        :file-list="fileList"
        :data="{batchNumber:extraParam.batchNumber}"
        :on-success="uploadFinish"
        :on-change="handleFileChange"
        :on-preview="showFileList"
        :before-upload="handleBeforeUpload"
        :on-remove="handleRemove2"
        class="upload-demo"
        action="http://localhost:8082/demo/admin/iorder/uploadExcels"
        multiple
        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, .xlsx">

        <el-button sizi="mini" class="filter-item" type="primary" @click="uploadDoc(batchNumber)">
          上传订单文件
          <i class="el-icon-upload el-icon&#45;&#45;right"/>
        </el-button>
      </el-upload>
      <br>
      <el-checkbox-group v-model="checkedFileIndices">
        <el-checkbox
          v-for="(file, index) in fileList"
          :key="file.name"
          :label="index"
        >
          {{ file.name }}
        </el-checkbox>
      </el-checkbox-group>
      <br>
      <el-button sizi="mini" type="primary" icon="el-icon-edit" @click="handleToDatabase">确认上传
      </el-button>
      <el-button sizi="mini" type="primary" icon="el-icon-edit" @click="mergeSelectFile">合并选中文件
      </el-button>
      <el-button sizi="mini" type="primary" icon="el-icon-edit" @click="cancelMerge">撤销
      </el-button>

      </div>


    <el-card v-if="showCard" class="box-card">

      <el-table
        v-loading="listLoading"
        :data="listProductCount"
        :header-cell-style="{fontSize: '16px', backgroundColor: '#ffff66',color:'#333'}"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row>
        <el-table-column align="center" min-width="60" label="生产日期" prop="productionDate"/>
        <el-table-column align="center" min-width="80" label="产品总活度(Ci)" prop="totalC"/>
        <el-table-column align="center" min-width="90" label="产品总体积(ml)" prop="totalV"/>
        <el-table-column align="center" min-width="90" label="此次分装活度(Ci)" prop="orderTotalActivity"/>
        <el-table-column align="center" min-width="90" label="此次分装体积(ml)" prop="orderCountVolume"/>
        <el-table-column align="center" min-width="80" label="剩余体积(ml)" prop="remainingVolume"/>
        <el-table-column align="center" min-width="80" label="剩余活度(Ci)" prop="remainingActivity"/>
      </el-table>

    </el-card>

    <el-card v-if="showCard2" class="box-card">
      <el-table
        v-loading="listLoading"
        :data="listCf"
        :header-cell-style="{fontSize: '16px', backgroundColor: '#00ffcc',color:'#333'}"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row>
        <el-table-column align="center" min-width="80" label="国药准字H10983121" prop="cf121"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983120" prop="cf120"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983119" prop="cf119"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983122" prop="cf122"/>
        <el-table-column align="center" min-width="60" label="总数" prop="cfTotal"/>
      </el-table>
    </el-card>

    <!--生成备货/备货查询-->
    <el-card v-show="false" class="box-card">
      <el-table
        v-loading="listLoading"
        :data="listCf"
        :header-cell-style="{fontSize: '16px', backgroundColor: '#00ffcc',color:'#333'}"
        size="small"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row>
        <el-table-column align="center" min-width="80" label="国药准字H10983121" prop="cf121"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983120" prop="cf120"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983119" prop="cf119"/>
        <el-table-column align="center" min-width="90" label="国药准字H10983122" prop="cf122"/>
        <el-table-column align="center" min-width="60" label="总数" prop="cfTotal"/>
      </el-table>
    </el-card>

    <!-- 以下为备货的查询信息 -->
    <!-- 以下为备货的查询信息 -->
    <el-table
      v-loading="listLoading"
      v-if="showStock"
      :data="listStockss"
      :header-cell-style="{fontSize: '16px', backgroundColor: '#ffbb2c',color:'#333'}"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row>
      <el-table-column align="center" min-width="50" label="" type="selection"/>
      <el-table-column align="center" min-width="50" label="显示序号" prop="showId"/>
      <el-table-column align="center" min-width="80" label="产品批号" prop="batchNumber"/>
      <el-table-column align="center" min-width="90" label="收货单位" prop="userName"/>
      <el-table-column align="center" min-width="70" label="发货方式" prop="deliveryType"/>
      <el-table-column align="center" min-width="60" label="订量" prop="orderCount"/>
      <el-table-column align="center" min-width="100" label="使用时间" prop="useTime"/>
      <el-table-column align="center" min-width="50" label="件数" prop="pieces"/>

      <el-table-column align="center" min-width="80" label="分装体积(ml)" prop="volume"/>
      <el-table-column align="center" min-width="80" label="实际分装活度(mCi/件)" prop="activity"/>

      <el-table-column align="center" label="操作" width="150px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button type="primary" size="mini" @click="handleUpdate2(scope.row)" style="margin-left: 0px;">编辑</el-button>-->
          <!--<el-button type="primary" size="mini" @click="handleUpdate2(scope.row)">确认</el-button>-->
          <el-button type="danger" size="mini" @click="handleDelete(scope.row, index)">删除</el-button>

        </template>
      </el-table-column>

    </el-table>
    <!--<pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="showStocks"/>-->

    <!-- 以上为备货的查询信息 -->
    <!-- 以上为备货的查询信息 -->
    <!-- 添加或修改对话框 -->

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :row-class-name="tableRowClassName"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column align="center" min-width="40" label="选中" prop="isSelected" type="selection">
        <!--<template slot-scope="scope" >
          <el-checkbox v-model="checked" ></el-checkbox>
        </template>-->
      </el-table-column>
      <el-table-column type="expand" label="详情">
        <template slot-scope="props">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="生产日期">
              <span>{{ props.row.productionDate }}</span>
            </el-form-item>
            <el-form-item label="订单编号">
              <span>{{ props.row.orderNum }}</span>
            </el-form-item>
            <el-form-item label="订单行编号">
              <span>{{ props.row.orderLineNum }}</span>
            </el-form-item>
            <el-form-item label="地址">
              <span>{{ props.row.address }}</span>
            </el-form-item>
            <el-form-item label="联系人">
              <span>{{ props.row.consignee }}</span>
            </el-form-item>
            <el-form-item label="联系人电话">
              <span>{{ props.row.consigneeTelephone }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="50" label="序号" prop="showId"/>
      <el-table-column align="center" min-width="90" label="收货单位" prop="customerName">
        <template slot-scope="scope">
          <el-select
            v-if="showEditInput"
            @blur="handleBlurUserName(scope.row)"
            clearable
            filterable
            v-model="scope.row.customerName"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;">
            <el-option
              v-for="(value, key) in customerNames"
              :key="key"
              :label="value"
              :value="value"/>
          </el-select>

          <div v-else>{{ scope.row.customerName }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="60" label="发货日期" prop="date"/>
      <el-table-column align="center" min-width="70" label="发货方式" prop="deliveryType">
        <template slot-scope="scope">
          <el-select
            v-if="showEditInput"
            v-model="scope.row.deliveryType"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;">
            <el-option
              v-for="item in optionsType"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
           </el-select>

          <div v-else>{{ scope.row.deliveryType }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>

      </el-table-column>
      <el-table-column align="center" min-width="60" label="订量" prop="orderCount">
        <template slot-scope="scope">
          <el-input
            v-if="showEditInput"
            @blur="handleBlurOrderCount(scope.row)"
            v-model="scope.row.orderCount"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;"/>
          <div v-else>{{ scope.row.orderCount }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="100" label="使用时间" prop="useTime">
        <template slot-scope="scope">
          <el-date-picker
            v-if="showEditInput"
            v-model="scope.row.useTime"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @blur="handleBlurUseTime(scope.row)"
            type="date">
          </el-date-picker>
          <div v-else>{{ scope.row.useTime }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="60" label="产品批号" prop="materialBatch"/>

      <el-table-column align="center" min-width="80" label="实际发货件数" prop="pieces">
        <template slot-scope="scope">
          <el-input
            v-if="showEditInput"
            v-model="scope.row.pieces"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;"/>
          <div v-else>{{ scope.row.pieces }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="80" label="分装体积(ml)" prop="splitQuantity">
        <template slot-scope="scope">
          <el-input
            v-if="showEditInput"
            @blur="handleBlurSplitQuantity(scope.row)"
            v-model="scope.row.splitQuantity"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;"/>
          <div v-else>{{ scope.row.splitQuantity }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="80" label="实际分装活度(mCi/件)" prop="actualCount"/>
      <el-table-column v-if="showStockColumn" align="center" min-width="80" label="选用备货批号" prop="stockBatch"/>
      <el-table-column v-if="showStockColumn" align="center" min-width="80" label="选用备货Id" prop="stockId"/>

      <el-table-column align="center" min-width="100" label="备注" prop="notes">
        <template slot-scope="scope">
          <el-input
            v-if="showEditInput"
            v-model="scope.row.notes"
            style="width:100%;height: 100%;box-sizing: border-box;padding: 0;margin:0;font-size: 10px;"/>
          <div v-else>{{ scope.row.notes }}</div>
          <!-- @change="handleEdit(scope.$index, scope.row)"-->
        </template>
      </el-table-column>
      <el-table-column align="center" label="使用备货or删除" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button type="primary" size="mini" @click="handleUpdate2(scope.row)" style="margin-left: 0px;">编辑</el-button>-->
          <!--<el-button type="primary" size="mini" @click="handleUpdate2(scope.row)">确认</el-button>-->

          <el-button type="danger" size="mini" @click="handleDelete2(scope.row)">删除</el-button>
          <el-button type="primary" size="mini" @click="handleRollBack(scope.row)">撤销</el-button>

          <div>
            <!--<el-select v-model="scope.row.selectedItem" @change="handleSelectChange(scope.$index,scope.row)"-->
            <el-select
              ref="select"
              v-model="scope.row.selectedItem"
              placeholder="请选择备货"
              clearable>
              <el-option-group
                v-for="(group,index) in cacheStock"
                :key="index"
                :label="group.label"
                :value="group.value">
                <el-option
                  v-for="(item,subIndex) in group"
                  :key="subIndex"
                  :label="item.value"
                  :value="item.value"
                  @click.native="handleOptionClick(scope.row,scope.$index, index, subIndex)"/>
              </el-option-group>
            </el-select>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"/>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>

  </div>
</template>

<style>
  .el-dialog {
    width: 60%;
  }

  .table-expand {
    font-size: 0;
  }

  .input-container {
    display: flex;
    align-items: center;
  }

  .highlight-row {
    background-color: #f0f9eb; /* 浅绿色背景 */
  }

  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .flex-item {
    flex: 1; /* 让两个div等宽 */
    padding: 20px; /* 可选，添加一些内边距 */
    box-sizing: border-box; /* 使padding不影响flex的1:1比例 */
  }

  .stockRow {
    color: red;
  }

  .el-input {
    width: 100%;
    box-sizing: border-box; /* 确保padding不会增加元素的宽度 */
  }

  .custom-checkbox input[type="checkbox"] {
    width: 30px; /* 设置宽度 */
    height: 30px; /* 设置高度 */
    margin-top: 0; /* 可根据需要调整与其他元素的间距 */
  }

  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }

  .modified-row {
    background-color: red !important; /* 使用 !important 覆盖默认样式 */
  }

  .el-table .el-table__body tr.el-table__row.current-row {
    background-color: #f0f9eb; /* 你可以自定义颜色 */
  }

  .gallery {
    width: 80px;
    margin-right: 10px;
  }

  .highlight-row {
    background-color: yellow !important; /* 自定义高亮颜色 */
    font-weight: bold;
    font-size: 18px;
  }
</style>

<script>
import { deleteiorders,getEditInfos1, getEditInfos2,getEditInfos3,getEditInfos4,getEditInfos5 } from '@/api/business/iorder'
import os from 'os'
import { listdailyOrder, insertAlldailyOrder, getLocalIPv4} from '@/api/business/dailyOrder'
import {
  listBachNumbers,
  detailproductInfo,
  detailCF,
  createOrderList,
  createStock,
  catchTotalInfo,
  createShipAccord,
  getStringAfter,
  getOAsheet,
  listBachNumbers2,
  getValueByKey,
  getSplitSheet,
  getSplitSheet2
} from '@/api/business/productProduction'
import { showStock, listiorderStocks, listiorderStocks2, listiorderStocks3, editStock, getOneId, rollbackStock } from '@/api/business/iorderStock'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import axios from 'axios'
import { getLastTwoChars } from '../../api/business/iorderStock'
import { listCustomers, getNames } from '@/api/business/ioralCustomer'

export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: '/iorder/insertMany',
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
export default {
  name: 'IorderList',
  components: { BackToTop, Pagination },
  filters: {
    formatiorderType(iorderType) {
      if (iorderType === 1) {
        return '操作规程'
      } else if (iorderType === 2) {
        return '管理器材'
      } else {
        return '规章制度'
      }
    },
    formatPerson(personId) {
      if (personId === 0) {
        return '正常'
      } else if (personId === 1) {
        return '已过期'
      } else {
        return '已下架'
      }
    }
  },
  data() {
    return {
      list: [],
      listProductCount: [],
      uploadUrl: '',
      fileStock: [],
      listCf: [],
      listFiles: [],
      listStock: [],
      optionsType: [{
        value: '空运',
        label: '空运'
      }, {
        value: '汽运',
        label: '汽运'
      }, {
        value: '铁运',
        label: '铁运'
      }],
      stocks2: [],
      selectedStock: '',
      selectedValue: [],
      cascaderOptions: [],
      currentPage: 1,
      showStockColumn: false,
      categories: [],
      batchNumbers: [],
      batchNumbers2: [],
      pageize: '',
      total1: '',
      customerNames: [],
      highlightRow: false,

      highlightRow2: null,
      checked: true,
      radio4: '1',
      listStockss: [],
      multipleSelection: [],
      showCard: false,
      showCard4: false,
      cacheData: [],
      cacheStock: [],
      cacheStock2: [],
      editStockInfo: {
        id: 0,
        pieces: 2
      },
      showCard2: false,
      吃: false,
      stocks: [],
      options: [],
      selected: null,
      showStock: false,
      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: '管理员名称不能为空', trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      samples:{
        keepSample:'', //留样
        drawSample:'' //抽样
      },
      extraParam: {
        batchNumber: '',
        activity: '',
        remainActivity: '',
        remainVolume: ''
      },
      total: 0,
      fileLocation: '',
      fileList: [],
      checkedFileIndices: [], // 存储被选中的文件序号
      mergeList: [],
      batchNumber: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      value1: '',
      value2: '',
      stock: {
        id: '',
        showId: '',
        userName: '',
        batchNumber: '',
        volume: '',
        pieces: '',
        deliveryType: '',
        orderCount: '',
        useTime: '',
        activity: '',
        notes: '',
        selected: false
      },
      editQuery1:{   //订量编辑input失去焦点触发的查询参数
        actualCount:'',
        pieces:0,
        userName: '',

        orderCount: '',//订量
        useTime: '',
        batchNumber: '',
      },
      editQuery2:{   //分装体积编辑input失去焦点触发的查询参数
        pieces:0,
        splitQuantity:'',//分装体积
        userName: '',
        useTime: '',
        batchNumber: '',
      },
      listLoading: true,
      showEditInput:false,
      loading: false,
      date: new Date(),
      files: [],
      newAttachmentsTable: [],
      insert: true,
      remainActivity: '',
      remainVolume: '',
      activity: '',
      noPersonalInformation: [],
      splitListQuery:{
          keepSample:'',
          drawSample: '',
          multipleSelection:[]
       },
      listQuery: {
        page: 1,
        limit: 10,
        dailyOrder: {},
        iorders: {},
        /*      startTime: '',
                endTime: '',*/
        customerName: '',
        province: '',
        batchNumber: '',
        startToEnd: [],
        sort:'date',
        order:'desc'
      },
      ioralStockPageQuery:{
        page: 1,
        size:10,
        sort:'',
        order:''
      },

      iorderDetail: '',
      detailDialogVisible: false,
      downloadLoading: false,
      btnText: '',
      formData: [],
      fileListData: []
    }
  },
  created() {

    this.getBatchNumbers()
    this.fetchCascaderData()
    this.getLocalIPv4()
    this.getCustomerNames()
    /* this.fetchCascaderData()*/
  },

  mounted() {
    this.fetchCascaderData()
    console.log('mounted')
    this.getList()
    this.getCustomerNames()
    /*    this.fetchCascaderData()*/
  },
  /* computed: {
      reversedOptions() {
        // 返回倒序后的选项数组
        return this.batchNumbers.slice().reverse();
      }
    },*/
  methods: {
    fetchCascaderData() {
      // 假设有一个API可以获取级联数据
      /* this.$router.push({ path: '/iorderStock/', query: { id: row.id } }).then(response => {*/
      const stockQuery = {
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        sort:'volume',
        order:'desc',
      };
      listiorderStocks2(stockQuery).then(response => {
        /* axios.get('/iorderStock/categories').then(response =>{*/
        this.cacheStock = response.data.data.items
        console.log(this.cacheStock)
        // this.cacheStock2.options=this.cacheStock.options
        // this.options = this.cacheStock.options
      }).catch(() => {

      })
      this.cacheData.push({
        options: this.options
      })

      /* axios.get('/api/cascader-data').then(response => {
          this.cascaderOptions = response.data;
        });*/
    },
    handleCascaderChange(value) {
      // 处理级联选择改变的逻辑

    },
    handleOptionClick(row, rowIndex, groupIndex, optionIndex) {
      // 删除子选项
      console.log(optionIndex)
      const group = this.cacheStock[groupIndex]
      const selectedStockId = getStringAfter(row.selectedItem, 'id：')
      console.log(row.selectedItem)
      console.log(selectedStockId)
      const picc = 0
      /* getOneId(selectedStockId).then(response => {*/
      /* getOneId(selectedStockId).then(response => {
           picc=response.data.data.piece

        })*/

      const pieces = row.pieces

      if (row.stockId !== selectedStockId) {
        this.cacheData.push({
          id: row.id,
          splitQuantity: row.splitQuantity,
          pieces: row.pieces,
          actualCount: row.actualCount,
          orderCount: row.orderCount
        })

        /* this.cacheData.push(row);*/
        // 从后端获取数据
        this.editStockInfo.id = selectedStockId
        this.editStockInfo.pieces = pieces
        console.log(this.editStockInfo)

        editStock(this.editStockInfo).then(response => {
          /* console.log(response.data.data.items)*/
          this.cacheStock = response.data.data.items
        }).catch(error => {
          // 处理错误
          console.error('Error fetching such stockInfos:', error)
        })

        listiorderStocks3(row).then(response => {
          console.log(response.data)
          row.highlightRow = true
          row.productionDate = response.data.data.productionDate1
          row.orderCount = response.data.data.orderCount1
          row.splitQuantity = response.data.data.volume1
          row.pieces = response.data.data.pieces1
          row.actualCount = response.data.data.actualCount1
          row.materialBatch = response.data.data.batchNumber1
          row.stockBatch = response.data.data.batchNumber1
          row.stockId = response.data.data.stockId1

          console.log('Data received:', data)
        }).catch(error => {
          // 处理错误
          console.error('Error fetching data:', error)
        })
        /* group.splice(optionIndex, 1)*/

        // 这里判断当前件

        // 如果删除后该分组为空，也可以选择删除整个分组
        // if (group.options.length === 0) {
        //   this.tableData[rowIndex].options.splice(groupIndex, 1);
        // }
      }
      /* }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: '此备货数量小于订单数量，不能选择此备货'
            })
        })*/
    },

    handleBlurSplitQuantity(row){
      console.log('计算修改分装体积后的发货数据')//编辑状态失去焦点触发
      console.log(row.splitQuantity+'使用时间：'+row.useTime+'产品批号：'+row.materialBatch)
      this.editQuery2.pieces=row.pieces
      this.editQuery2.batchNumber=row.materialBatch
      this.editQuery2.splitQuantity=row.splitQuantity
      this.editQuery2.userName=row.customerName
      this.editQuery2.useTime=row.useTime
      getEditInfos2(this.editQuery2).then(response => {
           row.orderCount=response.data.data.orderCount;
           row.actualCount=response.data.data.actualCount;

      }).catch(error => {
        console.log(error)
      })

    },
    handleBlurOrderCount(row){
      console.log('计算修改订量后的发货数据')//编辑状态失去焦点触发
      console.log(row.orderCount+'使用时间：'+row.useTime+'产品批号：'+row.materialBatch)
      this.editQuery1.batchNumber=row.materialBatch
      this.editQuery1.pieces=row.pieces
      this.editQuery1.orderCount=row.orderCount
      this.editQuery1.userName=row.customerName
      this.editQuery1.useTime=row.useTime
      getEditInfos1(this.editQuery1).then(response => {
             row.splitQuantity=response.data.data.splitQuantity
             row.actualCount=response.data.data.actualCount;
             row.pieces=response.data.data.pieces;
      }).catch(error => {
        console.log(error)
      })
    },
    handleBlurUseTime(row){
      console.log('计算修改使用时间后的发货数据')//编辑状态失去焦点触发
      console.log(row.orderCount+'使用时间：'+row.useTime+'产品批号：'+row.materialBatch)
      this.editQuery1.batchNumber=row.materialBatch
      this.editQuery1.useTime=row.useTime
      this.editQuery1.pieces=row.pieces
      this.editQuery1.orderCount=row.orderCount
      this.editQuery1.userName=row.customerName
      getEditInfos4(this.editQuery1).then(response => {
        row.splitQuantity=response.data.data.splitQuantity
        row.actualCount=response.data.data.actualCount;
        row.pieces=response.data.data.pieces;
        /*row.pieces=response.data.data.pieces;*/
      }).catch(error => {
        console.log(error)
      })
    },
    /*handleBlurPieces(row){
      console.log('计算修改件数后的发货数据')//编辑状态失去焦点触发
      console.log(row.orderCount+'使用时间：'+row.useTime+'产品批号：'+row.materialBatch)
      this.editQuery1.batchNumber=row.materialBatch
      this.editQuery1.useTime=row.useTime
      this.editQuery1.pieces=row.pieces
      this.editQuery1.orderCount=row.orderCount
      this.editQuery1.actualCount=row.actualCount
      this.editQuery1.userName=row.customerName
      getEditInfos5(this.editQuery1).then(response => {
        row.orderCount=response.data.data.orderCount;
        /!*row.actualCount=response.data.data.actualCount;*!/
        /!*row.pieces=response.data.data.pieces;*!/

      }).catch(error => {
        console.log(error)
      })
    },*/
    handleBlurUserName(row){
      console.log('计算修改件用户名后的发货数据')//编辑状态失去焦点触发
      console.log(row.orderCount+'使用时间：'+row.useTime+'产品批号：'+row.materialBatch)
      this.editQuery1.batchNumber=row.materialBatch
      this.editQuery1.useTime=row.useTime
      this.editQuery1.pieces=row.pieces
      this.editQuery1.actualCount=row.actualCount
      this.editQuery1.orderCount=row.orderCount
      this.editQuery1.userName=row.customerName
      getEditInfos3(this.editQuery1).then(response => {
        row.splitQuantity=response.data.data.splitQuantity
        row.actualCount=response.data.data.actualCount;
      }).catch(error => {
        console.log(error)
      })
    },

    handleBeforeUpload() {
      this.list = []
    },
    handlePreview(file) {
      this.fileStock.map(fileName => {
        if (fileName === file.name) {
          this.list = this.fileStock[fileName]
        }
      })
      console.log('haha' + file.name)
    },
    // 获取字符串最后两个字符，用于提取备货的id信息
    handleDelete2(row) {
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
      this.$notify.success({
        title: '成功',
        message: '删除成功'
      })
    },

    getCustomerNames() {
      getNames(this.listQuery).then(response => {
        this.customerNames = response.data.data.items
      })
    },
    cancelMerge() {
      this.list = this.fileListData[0].data
    },
    mergeSelectFile() {
      /* const selectCheckbox=this.checkedFileIndices
        selectCheckbox.keys()*/
      /* const fileListPair = this.fileListData.find(item => item.name === file.name)*/
      /* console.log(this.checkedFileIndices)*/
      /* this.list=[]*/
      this.checkedFileIndices.map(element => {
        /* console.log(element)*/
        console.log(this.fileList[element].name)
        const xx = this.fileListData.find(item => item.name === this.fileList[element].name)
        /* console.log(xx)*/
        const yy = null
        this.mergeList = this.mergeList.concat(xx.data)
        console.log(xx.name)
        console.log(xx.data)
        /* this.list.push(xx.data)*/
      })
      this.list = this.mergeList

      /* this.fileListData.find()*/
    },

    handleRollBack1(row, column, event) {
      // 缓存当前行数据
      this.cacheData.push(row)
      // 你可以在这里做其他的处理，比如跳转页面等
    },
    /* 获取缓存，还原数据*/
    updateRowData(index, updatedData) {
      // 使用 Object.assign 来更新对象
      this.list.splice(index, 1, Object.assign({}, this.list[index], updatedData))
    },

    handleFileChange(file, fileList) {
      this.fileList = fileList
      // 可以在这里添加逻辑来处理新上传的文件，例如更新 checkedFileIndices
    },

    /* tableRowClassName({ row, rowIndex }) {
         if (this.highlightRow && row.id === this.highlightRow.id) {
           return 'highlight-row';
         }
         return '';
       },*/
    getBatchNumbers() {
      listBachNumbers2(this.listQuery).then(response => {
        this.batchNumbers = response.data.data.batchNumbers/* .sort((a, b) => new Date(a) - new Date(b))*/
        /*     this.batchNumbers=this.batchNumbers2.slice().reverse()*/
        /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
      }).catch(() => {
        console.log('getList catch')
        /* this.listStockss = []
          /!*this.total1 = 0*!/
          this.listLoading = false*/
      })
    },
    sortDates() {
      // 使用JavaScript的Array.prototype.sort()函数进行日期排序
      this.sortedDates = this.dates.sort((a, b) => new Date(a) - new Date(b))
    },
    showFileList(file) {
      this.list = []
      this.$nextTick(() => {
        const fileListPair = this.fileListData.find(item => item.name === file.name)
        console.log(fileListPair)
        // const fileList = fileListPair ? fileListPair.value : undefined
        this.list = fileListPair.data
        this.total = this.list.length
      }, 200)
    },

    uploadFinish(res, file) {
      this.list = res
      this.total = res.length
      console.log(res)
      this.fileListData.push({
        name: file.name,
        data: res
      })
      this.list.forEach(row => {
        this.cacheData[row.id] = { ...row }
      })
    },
    handleRemove2(index) {
      // 删除文件
      /* if (index !== undefined) {*/
      // this.fileList.splice(index, 1)
      /* }*/
    },
    selectStock(row) {
      this.listQuery.batchNumber = row.batchNumber
      listiorderStocks2(this.listQuery).then(response => {

      }).catch(() => {
        console.log('getList catch')
        this.listStockss = []
        /* this.total1 = 0*/
        this.listLoading = false
      })
      /* row.*/
    },
    userStocks() {
      /* var Params = {currentPage :this.currentPage,pagesize:this.pagesize};
        requestall(Params).then(resp=>{
          this.usertabledata=resp.page.list;
          this.total1 = resp.page.total;
        })*/
      const stockQuery = {
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        sort:'volume',
        order:'desc',
      };
      listiorderStocks(stockQuery).then(response => {
        this.listStockss = response.data.data.items.list
        this.total1 = response.data.data.items.total
      }).catch(() => {
        console.log('getList catch')
        this.listStockss = []
        /* this.total1 = 0*/
        this.listLoading = false
      })
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex

      if (row.highlightRow == true) { // 假设我们要高亮显示第三行（索引从0开始）
        return 'highlight-row'
      } else if (row.highlightRow == false) {
        return ''
      }
    },
    /* rowClassName({ row, rowIndex }) {
        if (rowIndex === 特定行的索引) {
          return '特定的类名'; // 这个类名定义了颜色
        } else {
          return '';
        }
      },*/

    handleSelectChange(index, row) {
      console.log(row)

      this.cacheData.push({
        id: row.id,
        splitQuantity: row.splitQuantity,
        pieces: row.pieces,
        actualCount: row.actualCount,
        orderCount: row.orderCount
      })

      /* this.cacheData.push(row);*/
      // 从后端获取数据
      listiorderStocks3(row).then(response => {
        console.log(response.data)
        row.highlightRow = trueq
        row.productionDate = response.data.data.productionDate1
        row.orderCount = response.data.data.orderCount1
        row.splitQuantity = response.data.data.volume1
        row.pieces = response.data.data.pieces1
        row.actualCount = response.data.data.actualCount1
        row.materialBatch = response.data.data.batchNumber1
        row.stockBatch = response.data.data.batchNumber1
        row.stockId = response.data.data.stockId1

        console.log('Data received:', data)
      }).catch(error => {
        // 处理错误
        console.error('Error fetching data:', error)
      })
      /* this.$delete(this.cacheStock, index)*/
      /* this.cacheStock.options.splice(index,1)*/
    },
    updateData(id, updatedData) {
      // 更新缓存中的数据
      this.cacheData[id] = { ...this.cacheData[id], ...updatedData }
      // 更新表格数据源
      this.list = this.list.map(row => {
        if (row.id === id) {
          return { ...row, ...updatedData }
        }
        return row
      })
    },
    // 更新行数据的示例方法
    /* updateRowData(index, newData) {
        // 执行更新操作
        this.list[index] = newData
      },*/

    highlightRowHandler(row) {
      this.highlightRow2 = row
    },
    fetchDataFromBackend(selectedValue, row) {
      // 这里使用axios或其他HTTP客户端发起请求
      // 假设你已经安装并配置了axios

      return axios.get('/api/data?selected=' + selectedValue + '&row=' + JSON.stringify(row))
        .then(response => {
          /* response.data*/
        })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.currentPage = 1
      this.userStocks()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.userStocks()
    },

    toggleCard() {
      this.showCard = !this.showCard // 切换卡片的显示状态
      if (this.showCard == false) {
        getProductInfo()
      } else {

      }
    },
    toggleCard2() {
      this.showCard2 = !this.showCard2 // 切换卡片的显示状态
      if (this.showCard2 == false) {

      } else {

      }
    },
    handleSelectionChange(val2) {
      this.multipleSelection = val2
      /* detailproductInfo(this.multipleSelection).then(response => {
          this.listProductCount = response.data.data.items
          this.listLoading = false

        }).catch(() => {
          console.log('getList catch')
          this.listProductCount = []
          this.total = 0
          this.listLoading = false
        })*/
    },

    open2() {
      detailproductInfo(this.extraParam.batchNumber).then(response => {
        /* this.list = response.data.data.items
          this.total = response.data.data.total*/
        console.log(response.data.data.productProduction.remainActivity)
        this.$notify({
          title: '产品信息提示',
          message: this.extraParam.batchNumber + '/n' + response.activity + '/n' + response.data.remainActivity + '/n' + response.data.remainVolume,
          duration: 0
        })
      }).catch(() => {
        this.listLoading = false
      })
    },
    importData() {
      const myfile = this.$refs.myfile
      const files = myfile.files
      const file = files[0]
      var formData = new FormData()
      formData.append('file', file)
      this.uploadFileRequest('/admin/demo/iorder/insertMany', formData).then(resp => {
        if (resp) {
          console.log(resp)
        }
      })
    },
    getList() {
      console.log('getList')
      this.listLoading = true

      listdailyOrder(this.listQuery).then(response => {
        console.log('getList then')
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    getProductInfo() {
      this.showCard = !this.showCard // 切换卡片的显示状态
      if (this.showCard == false) {
      } else {
        console.log('productInfo')
        this.listLoading = true
        detailproductInfo(this.multipleSelection).then(response => {
          this.listProductCount = response.data.data.items
          this.listLoading = false
        }).catch(() => {
          console.log('getList catch')
          this.listProductCount = []
          this.total = 0
          this.listLoading = false
        })
      }
    },

    getCF() {
      this.showCard2 = !this.showCard2 // 切换卡片的显示状态
      if (this.showCard2 == false) {
      } else {
        console.log('CFinfo')
        this.listLoading = true
        detailCF(this.multipleSelection).then(response => {
          this.listCf = response.data.data.items
          this.listLoading = false
        }).catch(() => {
          console.log('getList catch')
          this.listCf = []
          this.total = 0
          this.listLoading = false
        })
      }
    },

    getTotalInfo() {
      console.log('orderCountListinfo')
      this.listLoading = true
      catchTotalInfo(this.multipleSelection).then(response => {
        /* this.list = response.data.data.items*/
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    /* 生成分装单*/
    getSplitSheets() {
      console.log('getSplitSheets')
      this.listLoading = true
      getSplitSheet(this.multipleSelection).then(response => {
        /* this.list = response.data.data.items*/
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    /* 生成分装清单*/
    getSplitSheets2() {
      console.log('getSplitSheets2')
      this.listLoading = true
      /*
      this.splitListQuery.drawSample=this.samples.drawSample
      this.splitListQuery.keepSample=this.samples.keepSample
      this.splitListQuery.multipleSelection=this.multipleSelection
      console.log(this.multipleSelection)*/
      const dataToSend = {
        drawSample: this.samples.drawSample,
        keepSample: this.samples.keepSample,
        iordersTemplates: this.multipleSelection // 直接发送整个数组
      };
      getSplitSheet2(dataToSend).then(response => {
        /* this.list = response.data.data.items*/
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        /*this.list = []
        this.total = 0*/
        this.listLoading = false
      })
    },

    getOrderCountList() {
      console.log('orderCountListinfo')
      this.listLoading = true
      createOrderList(this.list).then(response => {
        this.list = response.data.data.items
        this.listLoading = false
        this.$notify({
          title: '提示',
          message: '已生成订单信息总表，位置在：' + response.data.data.fileLocation,
          duration: 4000
        })
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },

    getShipAccord() {
      console.log('getShipAccord')
      this.listLoading = true
      createShipAccord(this.multipleSelection).then(response => {
        this.list = response.data.data.items
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },

    getOAAccord() {
      console.log('getOAAccord')
      /* this.listLoading = true*/
      getOAsheet(this.multipleSelection).then(response => {
        /* this.list = response.data.data.items
          this.listLoading = false*/

      }).catch(() => {
        console.log('getList catch')
        /* this.list = []
          this.total = 0
          this.listLoading = false*/
      })
    },

    getNullList() {
      console.log('refresh')
      this.listLoading = true
      this.listQuery.dailyOrder = null
      listdailyOrder(this.listQuery).then(response => {
        console.log('refresh then')
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        console.log('getList catch')
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    uploadDoc(batchNumber) {
      /* this.fileList.size=0*/
      this.batchNumber = this.data.batchNumber
    },
    handleToDatabase() {
      console.log(this.multipleSelection)
      this.listLoading = true
      insertAlldailyOrder(this.multipleSelection).then(response => {
        console.log('refresh then')
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
        this.$notify.success({
          title: '成功',
          message: '上传成功，请查看该次订货分装汇总表'
        })
      }).catch(() => {
        console.log('getList catch')
        /* this.list = []*/
        /* this.total = 0*/
        this.listLoading = false
        this.$notify.error({
          title: '上传失败,分装量超出剩余量',
          message: '上传失败,分装量超出剩余量'
        })
      })
    },

    handleCalculate() {
      console.log('handleCalculate')
    },

    showStocks() {
      this.showStock = !this.showStock
      if (this.showStock === false) {
      } else {
        console.log('CFinfo')
        /* this.listLoading = true*/
        listiorderStocks(this.listQuery).then(response => {
          this.listStockss = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          console.log('getList catch')
          this.listStockss = []
          this.total = 0
          this.listLoading = false
        })
      }
    },

    createStocks() {
      this.showStock = !this.showStock
      if (this.showStock === false) {
      } else {
        console.log('CFinfo')
        /* this.listLoading = true*/
        createStock(this.list).then(response => {
          this.listStockss = response.data.data.items
          this.listLoading = false
        }).catch(() => {
          console.log('getList catch')
          this.listStockss = []
          this.total = 0
          this.listLoading = false
        })
      }
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.$router.push({ path: '/iorders/create' })
    },
    handleUpdate2() {
      /* this.$router.push({ path: '/iorders/editDailyOrder', query: { id: row.id } })*/
      this.showEditInput = !this.showEditInput
    },

    /* handleDelete(row, index) {
        this.list.splice(index, 1)
      },*/
    /* 撤销选用备货的操作，恢复订单数据 */
    handleRollBack(row) {
      const stockId = getLastTwoChars(row.selectedItem)
      const piece = row.pieces
      this.editStockInfo.id = stockId
      this.editStockInfo.pieces = piece
      rollbackStock(this.editStockInfo).then(response => {
        this.cacheStock = response.data.data.items
      }).catch(error => {
        // 处理错误
        console.error('Error fetching such stockInfos:', error)
      })
      /*this.list.map(row => {*/
        this.cacheData.map(item => {
          if (row.id === item.id) {
            /* console.log(item.orderCount)*/
            console.log(item)
            row.pieces = item.pieces
            console.log("备货信息："+this.cacheData)
            row.actualCount = item.actualCount
            console.log("备货实际分装量："+item.actualCount)
            row.splitQuantity = item.splitQuantity
            row.stockId = null
            /* row.selectedItem=''*/
            return row.orderCount = item.orderCount
            // Object.assign(row, 'orderCount', item.orderCount)
          }
        })
    /*  })*/
      /* const stockId = getLastTwoChars(row.selectedItem)
        this.cacheStock2.forEach(group => {
          if (group.label.includes(row.stockBatch)) {
            group.options.forEach(option => {
              if (option.value.includes('id：' + stockId)) {
                this.cacheStock.forEach(group2 => {
                  if (group2.label.includes(row.stockBatch)) {
                    this.cacheStock.push({
                      options: this.options
                    })
                  }
                })
              }
            })
          }

        })*/
      console.log(this.list)
      row.selectedItem = ''
      row.highlightRow = false
    },
    updateRow(id, updatedData) {
      const index = this.list.findIndex(row => row.id === id)
      if (index !== -1) {
        this.list.splice(index, 1, { ...this.list[index], ...updatedData })
      }
    },
    handleUpdate(row) {
      this.$router.push({ path: '/iorder/edit', query: { id: row.id }})
    },
    showDetail(detail) {
      this.iorderDetail = detail
      this.detailDialogVisible = true
    },
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '发货日期', '件数', '包装材料ID', '空运订量', '铁运订量', '汽运订量', '产品批号', '分装量', '活度', '测量时间', '生产量', '剩余量', '邻碘马尿酸钠', '备注']
          const filterVal = ['id', 'date', 'pieces', 'packageId', 'orderCount1', 'orderCount2', 'orderCount3', 'batchNumber', 'splitCount', 'activity', 'mearsureTime', 'remarks', 'iorderStatus', 'overdue']
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '碘131化钠口服溶液订单信息表')
          this.downloadLoading = false
        })
    }
  }
}
</script>
